package cn.iocoder.yudao.module.robot.api;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.module.robot.api.record.RobotCallRecordApi;
import cn.iocoder.yudao.module.robot.client.dto.RobotClueRespDTO;
import cn.iocoder.yudao.module.robot.dal.dataobject.callrecord.RobotCallRecordDO;
import cn.iocoder.yudao.module.robot.dal.dataobject.callrecordbills.CallRecordBillsDO;
import cn.iocoder.yudao.module.robot.dal.mysql.callrecord.RobotCallRecordMapper;
import cn.iocoder.yudao.module.robot.dal.mysql.callrecordbills.CallRecordBillsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class RobotCallRecordApiImpl implements RobotCallRecordApi {

    @Resource
    private RobotCallRecordMapper robotCallRecordMapper;

    @Resource
    private CallRecordBillsMapper callRecordBillsMapper;

    @Override
    public Long addCallRecord(RobotClueRespDTO clue) {
        return TenantUtils.execute(clue.getTenantId(), () -> {
            if (robotCallRecordMapper.selectOne(RobotCallRecordDO::getRobotCallRecordId, clue.getRobotCallRecordId()) == null) {
                RobotCallRecordDO callRecord = BeanUtils.toBean(clue, RobotCallRecordDO.class);
                robotCallRecordMapper.insert(callRecord);
                Long callRecordId = callRecord.getId();
                clue.getBills().forEach(bill -> {
                    CallRecordBillsDO billCreateDO = BeanUtils.toBean(bill, CallRecordBillsDO.class);
                    billCreateDO.setCallRecordId(callRecordId);
                    callRecordBillsMapper.insert(billCreateDO);
                });
                return callRecordId;
            }
            return null;
        });

    }

    @Override
    public Long getCallRecordCountByMobile(Long taskId, String mobile) {
        return robotCallRecordMapper.selectCount(new LambdaQueryWrapperX<RobotCallRecordDO>().eq(RobotCallRecordDO::getTaskId, taskId).eq(RobotCallRecordDO::getMobile, mobile));
    }
}
